package com.shanlitech.bluetooth.map;

import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;

import java.util.ArrayList;
import java.util.List;

public class DragDetector {
    private static final String TAG = "Map2D";
    private final List<Draggable> objects = new ArrayList<>();
    private final WindowMapCoordinator coordinator;
    private Draggable dragging = null;
    private float lastX = 0;
    private float lastY = 0;

    public DragDetector(WindowMapCoordinator coordinator) {
        this.coordinator = coordinator;
    }

    public void addObject(Draggable obj) {
        objects.add(obj);
    }

    public void remove(Draggable obj) {
        objects.remove(obj);
    }

    public boolean onTouchEvent(MotionEvent ev) {
        boolean rc = false;
        switch(ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if( ev.getPointerCount() == 1 ) {
                    lastX = ev.getX();
                    lastY = ev.getY();
                    dragging = findObject(lastX,lastY);
                    rc = (dragging != null);
                    Log.d(TAG,"found " + (rc ? "object" : "nothing") + " at " + lastX + "," + lastY);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if( ev.getPointerCount() == 1 ) {
                    if( dragging != null ) {
                        float moveX = ev.getX() - lastX;
                        float moveY = ev.getY() - lastY;
                        lastX = ev.getX();
                        lastY = ev.getY();
                        dragging.move(moveX,moveY,coordinator);
                        rc = true;
                    }
                } else {
                    dragging = null;
                }
                break;
            case MotionEvent.ACTION_UP:
                dragging = null;
                break;
            default:
                break;
        }
        return rc;
    }

    private Draggable findObject(float x,float y) {
        for(int i=objects.size() - 1; i >= 0; --i) {
            final Draggable obj = objects.get(i);
            final Rect rect = obj.getObjectRect(coordinator);
            if( rect.contains((int)x,(int)y) ) {
                return obj;
            }
        }
        return null;
    }
}
